package com.taptech.doufu.net.httputils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;

import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.util.UIUtil;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by lsy on 2015/9/28.
 */
public class DownloadTask extends AsyncTask<String, Integer , String> {

    Context context;

    public DownloadTask(Context context){
        this.context = context;
    }

    @Override
    protected String doInBackground(String... strings) {
        String fileUrl = strings[0];
        String fileName = strings[1];
        String expandName = strings[2];

        try {
            URL u = new URL(fileUrl);
            InputStream is = u.openStream();

            DataInputStream dis = new DataInputStream(is);

            byte[] buffer = new byte[1024];
            int length;

            FileOutputStream fos = new FileOutputStream(new File(fileName + expandName));
            while ((length = dis.read(buffer))>0) {
                fos.write(buffer, 0, length);
            }
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(new File(Constant.AppDir.DIR_HOME + fileUrl.hashCode() + expandName));
            intent.setData(uri);
            context.sendBroadcast(intent);

        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SecurityException se) {
            se.printStackTrace();
        }

        return (fileName+expandName);
    }

    @Override
    protected void onPostExecute(String fileName) {
        UIUtil.toastMessage(context, "下载成功，图片已保存至:" + fileName);

    }

    public void startDownload(String fileName , String fileUrl , String expandName){
        String[] strings = new String[3];
        strings[0] = fileUrl;
        strings[1] = fileName;
        strings[2] = expandName;
        this.execute(strings);
    }


}
